<template>
  <div>
    <el-form-item label="主图" prop="main_image">
      <el-upload
        class="avatar-uploader"
        action="http://127.0.0.1:5050/system/upload-file"
        :show-file-list="false"
        :before-upload="beforeAvatarUpload"
        :on-success="handleAvatarSuccess"
      >
        <img v-if="modelValue.main_image" :src="modelValue.main_image" class="h-50 w-50" alt="商品主图" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>
    <el-form-item>
      <!-- 2. 新增：粘贴链接 -->
      <el-input v-model="main_image" placeholder="或输入主图图片链接（可选）" style="width: 500px" />
    </el-form-item>
    <el-form-item label="商品图册" prop="images">
      <div class="gallery-container">
        <!-- 可拖拽的图片列表 -->
        <div class="gallery-grid" @dragover.prevent @drop="handleDrop">
          <div
            v-for="(item, index) in fileList"
            :key="item.uid || index"
            class="gallery-item"
            :draggable="true"
            @dragstart="handleDragStart($event, index)"
            @dragenter.prevent="handleDragEnter($event, index)"
            @dragover.prevent
          >
            <div class="image-wrapper">
              <img :src="item.url" alt="商品图片" class="gallery-image" />
              <div class="image-overlay">
                <el-icon class="preview-icon" @click="handlePictureCardPreview(item as any)">
                  <ZoomIn />
                </el-icon>
                <el-icon class="delete-icon" @click="handleRemoveByIndex(index)">
                  <Delete />
                </el-icon>
                <el-icon class="drag-icon">
                  <Rank />
                </el-icon>
              </div>
            </div>
          </div>

          <!-- 上传按钮 -->
          <el-upload
            action="http://127.0.0.1:5050/system/upload-file"
            :show-file-list="false"
            :on-success="handleGallerySuccess"
            :before-upload="beforeAvatarUpload"
            class="upload-item"
          >
            <div class="upload-placeholder">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <div class="upload-text">上传图片</div>
            </div>
          </el-upload>
        </div>
      </div>
    </el-form-item>
    <el-form-item>
      <!-- 图册链接输入 -->
      <div class="flex items-center gap-2">
        <el-input
          v-model="galleryLinkInput"
          placeholder="输入图片链接添加到图册"
          style="width: 400px"
          @keyup.enter="addGalleryLink"
        />
        <el-button type="primary" :disabled="!galleryLinkInput.trim()" @click="addGalleryLink">
          添加到图册
        </el-button>
      </div>
    </el-form-item>
    <el-form-item label="商品详情" prop="detail_html">
      <!-- <Vditor
        v-model="detailHtml"
        :options="{
          height: 560, // 高度
          outline: { enable: true, position: 'right' } // 大纲
        }"
      /> -->
      <WangEditorBase v-if="editorKey > 0" :key="editorKey" ref="wangEditorRef" v-model="detailHtml" />
    </el-form-item>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from "vue";
import type { UploadProps, UploadUserFile } from "element-plus";
import { ElMessage } from "element-plus";
import { Delete, Plus, Rank, ZoomIn } from "@element-plus/icons-vue";
// import Vditor from "@/components/Vditor.vue"; // 引入 Vditor 组件
import WangEditorBase from "@/components/wangEditorBase.vue";

const wangEditorRef = ref();
const editorKey = ref(1); // 用于强制重新渲染 WangEditor，初始值设为1
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(["update:modelValue"]);

const fileList = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const galleryLinkInput = ref("");
const draggedIndex = ref<number | null>(null);

// 初始化编辑器
onMounted(() => {
  // 确保编辑器在组件挂载后正确初始化
  nextTick(() => {
    // 延迟一点时间确保 DOM 完全渲染
    setTimeout(() => {
      editorKey.value = Date.now(); // 使用时间戳确保唯一性
      console.log("GoodsDetail: 编辑器初始化，editorKey =", editorKey.value);
    }, 200);
  });
});

//将 fileList 与 prop images 同步
watch(
  () => props.modelValue.images,
  newUrls => {
    if (newUrls && newUrls.length > 0 && fileList.value.length !== newUrls.length) {
      fileList.value = newUrls.map(url => ({ name: "", url }));
    }
  },
  { immediate: true }
);
// 将 detailHtml 与 prop detail_html 同步
const detailHtml = computed({
  get: () => {
    return props.modelValue.detail_html || "";
  },
  set: value => {
    emit("update:modelValue", { ...props.modelValue, detail_html: value });
  }
});
const main_image = computed({
  get: () => {
    return props.modelValue.main_image || "";
  },
  set: value => {
    emit("update:modelValue", { ...props.modelValue, main_image: value });
  }
});
// 处理主图头像上传
const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  const { data } = response;
  const updatedModel = {
    ...props.modelValue,
    main_image: import.meta.env.VITE_BASE_URL + data.url
  };
  console.log("主图响应", import.meta.env.VITE_BASE_URL);
  emit("update:modelValue", updatedModel);
  ElMessage.success("主图上传成功");
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = rawFile => {
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("图片必须是 JPG 或 PNG 格式!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error("图片大小不能超过 5MB!");
    return false;
  }
  return true;
};

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  const updatedUrls = uploadFiles.map(file => file.url);
  const updatedModel = { ...props.modelValue, images: updatedUrls };
  emit("update:modelValue", updatedModel);
};

const handlePictureCardPreview: UploadProps["onPreview"] = uploadFile => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

const handleGallerySuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  const { data } = response;
  const newImageUrl = import.meta.env.VITE_BASE_URL + data.url;

  // 添加到现有图片列表中，而不是替换
  const currentImages = props.modelValue.images || [];
  const updatedImages = [...currentImages, newImageUrl];
  const updatedModel = { ...props.modelValue, images: updatedImages };
  emit("update:modelValue", updatedModel);

  // 同时添加到 fileList 用于显示
  const newFile = {
    name: `uploaded_${Date.now()}`,
    url: newImageUrl,
    uid: Date.now()
  };
  fileList.value.push(newFile);

  ElMessage.success("图片上传成功");
};

const uploadImage = async (file: File): Promise<string> => {
  const formData = new FormData();
  formData.append("file", file);
  try {
    const response = await fetch("http://127.0.0.1:5050/system/upload-file", {
      method: "POST",
      body: formData
    });
    if (!response.ok) {
      throw new Error("Upload failed with status " + response.status);
    }
    const result = await response.json();
    if (result.data && result.data.url) {
      return import.meta.env.VITE_BASE_URL + result.data.url;
    } else {
      ElMessage.error(result.message || "图片上传失败");
      throw new Error(result.message || "图片上传失败");
    }
  } catch (error) {
    console.error("Image upload error:", error);
    ElMessage.error("图片上传失败");
    throw error;
  }
};

// 添加图册链接
const addGalleryLink = () => {
  const link = galleryLinkInput.value.trim();
  if (!link) {
    ElMessage.warning("请输入图片链接");
    return;
  }

  // 检查是否已存在
  const currentImages = props.modelValue.images || [];
  if (currentImages.includes(link)) {
    ElMessage.warning("该图片链接已存在");
    return;
  }

  // 添加到图册
  const updatedImages = [...currentImages, link];
  const updatedModel = { ...props.modelValue, images: updatedImages };
  emit("update:modelValue", updatedModel);

  // 同时添加到 fileList 用于显示
  const newFile = {
    name: `image_${Date.now()}`,
    url: link,
    uid: Date.now()
  };
  fileList.value.push(newFile);

  // 清空输入框
  galleryLinkInput.value = "";

  ElMessage.success("图片已添加到图册");
};

// 拖拽开始
const handleDragStart = (event: DragEvent, index: number) => {
  draggedIndex.value = index;
  if (event.dataTransfer) {
    event.dataTransfer.effectAllowed = "move";
  }
};

// 拖拽进入
const handleDragEnter = (event: DragEvent, index: number) => {
  event.preventDefault();
  if (draggedIndex.value !== null && draggedIndex.value !== index) {
    // 添加视觉反馈
    const target = event.currentTarget as HTMLElement;
    target.classList.add("drag-over");
  }
};

// 拖拽放置
const handleDrop = (event: DragEvent) => {
  event.preventDefault();
  const target = event.target as HTMLElement;
  const dropItem = target.closest(".gallery-item");

  if (dropItem && draggedIndex.value !== null) {
    const dropIndex = Array.from(dropItem.parentNode!.children).indexOf(dropItem);

    if (dropIndex !== -1 && dropIndex !== draggedIndex.value) {
      // 重新排序
      const newFileList = [...fileList.value];
      const draggedItem = newFileList.splice(draggedIndex.value, 1)[0];
      newFileList.splice(dropIndex, 0, draggedItem);

      fileList.value = newFileList;

      // 更新 modelValue.images
      const updatedImages = newFileList.map(file => file.url).filter(Boolean);
      const updatedModel = { ...props.modelValue, images: updatedImages };
      emit("update:modelValue", updatedModel);

      ElMessage.success("图片排序已更新");
    }
  }

  // 清理拖拽状态
  draggedIndex.value = null;
  document.querySelectorAll(".drag-over").forEach(el => {
    el.classList.remove("drag-over");
  });
};

// 通过索引删除图片
const handleRemoveByIndex = (index: number) => {
  const newFileList = [...fileList.value];
  newFileList.splice(index, 1);
  fileList.value = newFileList;

  // 更新 modelValue.images
  const updatedImages = newFileList.map(file => file.url).filter(Boolean);
  const updatedModel = { ...props.modelValue, images: updatedImages };
  emit("update:modelValue", updatedModel);

  ElMessage.success("图片已删除");
};
</script>

<style scoped>
.w-full {
  width: 100%;
}

/* 图册容器样式 */
.gallery-container {
  width: 100%;
}

.gallery-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(148px, 1fr));
  gap: 8px;
  width: 100%;
}

.gallery-item {
  position: relative;
  width: 148px;
  height: 148px;
  overflow: hidden;
  cursor: move;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: all 0.3s ease;
}

.gallery-item:hover {
  border-color: var(--el-color-primary);
}

.gallery-item.drag-over {
  background-color: var(--el-color-primary-light-9);
  border-color: var(--el-color-primary);
}

.image-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
}

.gallery-image {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  inset: 0;
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: center;
  background: rgb(0 0 0 / 50%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.gallery-item:hover .image-overlay {
  opacity: 1;
}

.preview-icon,
.delete-icon,
.drag-icon {
  padding: 4px;
  font-size: 26px;
  color: white;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.preview-icon:hover {
  background-color: rgb(255 255 255 / 20%);
}

.delete-icon:hover {
  background-color: rgb(245 108 108 / 80%);
}

.drag-icon:hover {
  background-color: rgb(255 255 255 / 20%);
}

.upload-item {
  width: 148px;
  height: 148px;
}

.upload-item :deep(.el-upload) {
  width: 100%;
  height: 100%;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: border-color 0.3s ease;
}

.upload-placeholder:hover {
  border-color: var(--el-color-primary);
}

.upload-icon {
  margin-bottom: 8px;
  font-size: 28px;
  color: #8c939d;
}

.upload-text {
  font-size: 14px;
  color: #8c939d;
}
</style>

<style>
.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  width: 98px;
  height: 98px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
</style>
